﻿using Common;
using Microsoft.AspNetCore.Mvc;
using MongoDB;
using MongoDB.Model;
using Quartz.Service;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;


namespace Quartz.Manage.ApiControllers
{
    [Route("api/[controller]")]
    [ApiController]
    [GlobalAuthorize]
    public class QuartzController : ControllerBase
    {
        private readonly IMongoDB _mongoDB;
        private readonly IQuartzStartup _quartzStartup;
        private readonly IApiService _apiService;
        public QuartzController(IMongoDB mongoDB, IQuartzStartup quartzStartup,
            IApiService apiService)
        {
            _mongoDB = mongoDB;
            _quartzStartup = quartzStartup;
            _apiService = apiService;
        }

        /// <summary>
        /// 获取任务管理列表
        /// </summary>
        /// <param name="taskName"></param>
        /// <param name="groupName"></param>
        /// <param name="createTime"></param>
        /// <param name="method"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<PageModel<Mongo_TaskManageModel>> Get(string taskName,string groupName,string createTime,string method,int page = 1,int limit = 10)
        {
            Expression<Func<Mongo_TaskManageModel, bool>> where = m => true;
            if (!taskName.IsNullOrWhiteSpace())
            {
                where = where.And(m => m.TaskName.Contains(taskName));
            }
            if (!groupName.IsNullOrWhiteSpace())
            {
                where = where.And(m => m.GroupName.Contains(groupName));
            }
            if (!createTime.IsNullOrWhiteSpace())
            {
                var TimeBegin = createTime.Split(" - ")[0].ToDateTime();
                var TimeEnd = createTime.Split(" - ")[1].ToDateTime().Value.AddDays(1);
                where = where.And(m => m.CreateTime >= TimeBegin);
                where = where.And(m => m.CreateTime < TimeEnd);
            }
            if (!method.IsNullOrWhiteSpace())
            {
                where = where.And(m => m.Method == method);
            }
            return await _mongoDB.GetCollection<Mongo_TaskManageModel>("Task_Manage").FindPageListAsync(where, m => m.CreateTime, "desc", limit, page);
        }

        /// <summary>
        /// 添加新任务
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> Post([FromBody] Mongo_TaskManageModel data)
        {
            var result = new ApiResult { Success = false, Message = "新增失败" };
            if (data != null)
            {
                var Collection = _mongoDB.GetCollection<Mongo_TaskManageModel>("Task_Manage");
                if (!data.TaskName.IsNullOrWhiteSpace())
                {
                    var tasks = await Collection.FindListAsync(m => m.TaskName == data.TaskName);
                    if (tasks.Count > 0)
                    {
                        result.Success = false;
                        result.Message = "此任务名已存在";
                        return result;
                    }
                }
                else
                {
                    result.Success = false;
                    result.Message = "请输入任务名";
                    return result;
                }
                if (data.GroupName.IsNullOrWhiteSpace())
                {
                    result.Success = false;
                    result.Message = "请输入组名";
                    return result;
                }
                if (data.TaskUrl.IsNullOrWhiteSpace())
                {
                    result.Success = false;
                    result.Message = "请输入接口地址";
                    return result;
                }
                if (data.TaskCron.IsNullOrWhiteSpace())
                {
                    result.Success = false;
                    result.Message = "请输入时间配置";
                    return result;
                }
                if (!data.RequestBody.IsNullOrWhiteSpace())
                {
                    if (!data.RequestBody.IsJson())
                    {
                        result.Success = false;
                        result.Message = "请求参数请输入正确的Json格式";
                        return result;
                    }
                }
                if (!data.Token.IsNullOrWhiteSpace())
                {
                    if (!data.Token.IsJson())
                    {
                        result.Success = false;
                        result.Message = "请求头请输入正确的Json格式";
                        return result;
                    }
                }
                if (data.AuthType.IsNullOrWhiteSpace())
                {
                    data.AuthType = "0";
                }
                if (data.IsTip == 1)
                {
                    data.MaxTipNum = data.MaxTipNum.HasValue ? data.MaxTipNum.Value : 1;
                    data.ErrorNumTip = data.ErrorNumTip.HasValue ? data.ErrorNumTip.Value : 1;
                }
                Mongo_TaskAuth TaskAuthInfo = null;
                if (data.AuthType != "0")
                {
                    TaskAuthInfo = await _mongoDB.GetCollection<Mongo_TaskAuth>("Task_Auth").FindInfoAsync(m => m.AuthGuid == data.AuthType);
                    if (TaskAuthInfo == null)
                    {
                        result.Success = false;
                        result.Message = "选择的验证方式已删除，请检查";
                        return result;
                    }
                }

                await Collection.InsertOneAsync(new Mongo_TaskManageModel
                {
                    guid = Guid.NewGuid().ToString(),
                    TaskName=data.TaskName,
                    GroupName=data.GroupName,
                    TaskUrl=data.TaskUrl,
                    Method=data.Method,
                    RequestBody=data.RequestBody,
                    BodyType=data.BodyType,
                    AuthType= TaskAuthInfo!=null ? TaskAuthInfo.AuthGuid:"0",
                    AuthName= TaskAuthInfo!=null ? TaskAuthInfo.AuthName:"无需验证",
                    TaskCron=data.TaskCron,
                    Token=data.Token,
                    IsOpen=0,
                    CreateTime= DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc),
                    ErrorNumTip=data.ErrorNumTip,
                    IsTip=data.IsTip,
                    MaxTipNum=data.MaxTipNum
                });
                result.Success = true;
                result.Message = "新增成功";
            }
            return result;
        }

        /// <summary>
        /// 编辑任务
        /// </summary>
        /// <param name="guid"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPut("{guid}")]
        public async Task<ApiResult> Put(string guid, [FromBody] Mongo_TaskManageModel data)
        {
            var result = new ApiResult { Success = false, Message = "修改失败" };
            if (!guid.IsNullOrWhiteSpace() && data != null)
            {
                var Collection = _mongoDB.GetCollection<Mongo_TaskManageModel>("Task_Manage");
                var oldTaskInfo = await Collection.FindInfoAsync(m => m.guid == guid);
                if (!data.TaskName.IsNullOrWhiteSpace())
                {
                    var tasks = await Collection.FindListAsync(m => m.TaskName == data.TaskName&&m.guid!= oldTaskInfo.guid);
                    if (tasks.Count > 0)
                    {
                        result.Success = false;
                        result.Message = "此任务名已存在";
                        return result;
                    }
                }
                else
                {
                    result.Success = false;
                    result.Message = "请输入任务名";
                    return result;
                }
                if (data.GroupName.IsNullOrWhiteSpace())
                {
                    result.Success = false;
                    result.Message = "请输入组名";
                    return result;
                }
                if (data.TaskUrl.IsNullOrWhiteSpace())
                {
                    result.Success = false;
                    result.Message = "请输入接口地址";
                    return result;
                }
                if (data.TaskCron.IsNullOrWhiteSpace())
                {
                    result.Success = false;
                    result.Message = "请输入时间配置";
                    return result;
                }
                if (!data.RequestBody.IsNullOrWhiteSpace())
                {
                    if (!data.RequestBody.IsJson())
                    {
                        result.Success = false;
                        result.Message = "请求参数请输入正确的Json格式";
                        return result;
                    }
                }
                if (!data.Token.IsNullOrWhiteSpace())
                {
                    if (!data.Token.IsJson())
                    {
                        result.Success = false;
                        result.Message = "请求头请输入正确的Json格式";
                        return result;
                    }
                }
                if (data.AuthType.IsNullOrWhiteSpace())
                {
                    data.AuthType = "0";
                }
                Mongo_TaskAuth TaskAuthInfo = null;
                if (data.AuthType != "0")
                {
                    TaskAuthInfo = await _mongoDB.GetCollection<Mongo_TaskAuth>("Task_Auth").FindInfoAsync(m => m.AuthGuid == data.AuthType);
                    if (TaskAuthInfo == null)
                    {
                        result.Success = false;
                        result.Message = "选择的验证方式已删除，请检查";
                        return result;
                    }
                }
                if (data.IsTip == 1)
                {
                    data.MaxTipNum = data.MaxTipNum.HasValue ? data.MaxTipNum.Value : 1;
                    data.ErrorNumTip = data.ErrorNumTip.HasValue ? data.ErrorNumTip.Value : 1;
                }
                var AuthType = TaskAuthInfo != null ? TaskAuthInfo.AuthGuid : "0";
                var AuthName = TaskAuthInfo != null ? TaskAuthInfo.AuthName : "无需验证";
                await Collection.UpdateAsync(new
                {
                    TaskName = data.TaskName,
                    GroupName = data.GroupName,
                    TaskUrl = data.TaskUrl,
                    Method = data.Method,
                    RequestBody = data.RequestBody,
                    BodyType = data.BodyType,
                    TaskCron = data.TaskCron,
                    Token = data.Token,
                    AuthType = AuthType,
                    AuthName = AuthName,
                    ErrorNumTip = data.ErrorNumTip,
                    IsTip = data.IsTip,
                    MaxTipNum = data.MaxTipNum
                }, new { guid = guid });
                //如果修改了时间配置，则需要重新配置任务
                if (oldTaskInfo.TaskCron != data.TaskCron)
                {
                    var NewTaskInfo = await Collection.FindInfoAsync(m => m.guid == guid);
                    Task.Factory.StartNew(() =>
                    {
                        _quartzStartup.DeleteTask(NewTaskInfo.guid).Wait();
                        if (NewTaskInfo.IsOpen == 1)
                        {
                            _quartzStartup.AddJob(NewTaskInfo).Wait();
                        }
                    });
                }
                result.Success = true;
                result.Message = "修改成功";
            }
            return result;
        }

        /// <summary>
        /// 开启或者关闭任务
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPut("openTask/{guid}")]
        public async Task<ApiResult> OpenTask(string guid, [FromBody] Mongo_TaskManageModel data)
        {
            var result = new ApiResult { Success = false, Message = "操作失败" };
            if (!guid.IsNullOrWhiteSpace() && data != null)
            {
                var Collection = _mongoDB.GetCollection<Mongo_TaskManageModel>("Task_Manage");
                var oldTaskInfo = await Collection.FindInfoAsync(m => m.guid == guid);
                if (oldTaskInfo != null)
                {
                    await Collection.UpdateAsync(new
                    {
                        IsOpen=data.IsOpen
                    }, new { guid = guid });
                    var NewTaskInfo = await Collection.FindInfoAsync(m => m.guid == oldTaskInfo.guid);
                    if (NewTaskInfo != null)
                    {
                        Task.Factory.StartNew(() =>
                        {
                            _quartzStartup.DeleteTask(NewTaskInfo.guid).Wait();
                            if (NewTaskInfo.IsOpen == 1)
                            {
                                _quartzStartup.AddJob(NewTaskInfo).Wait();
                            }
                        });
                        result.Success = true;
                        result.Message = "操作成功";
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 删除任务
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        [HttpDelete("{guid}")]
        public async Task<ApiResult> Delete(string guid)
        {
            var result = new ApiResult { Success = false, Message = "删除失败" };
            if (!guid.IsNullOrWhiteSpace())
            {
                var Collection = _mongoDB.GetCollection<Mongo_TaskManageModel>("Task_Manage");
                var TaskInfo = await Collection.FindInfoAsync(m => m.guid == guid);
                if (TaskInfo != null)
                {
                    await Collection.DeleteAsync(new
                    {
                        guid = guid
                    });
                    _quartzStartup.DeleteTask(TaskInfo.guid);
                }
                result.Success = true;
                result.Message = "删除成功";
            }
            return result;
        }

        /// <summary>
        /// 手动调用
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        [HttpPost("sendApi/{guid}")]
        public async Task<ApiResult> SendApi(string guid)
        {
            var result = new ApiResult { Success = false, Message = "调用失败" };
            if (!guid.IsNullOrWhiteSpace())
            {
                var TaskManage = await _mongoDB.GetCollection<Mongo_TaskManageModel>("Task_Manage").FindInfoAsync(m => m.guid == guid);
                if (TaskManage != null)
                {
                    try
                    {
                        if (TaskManage != null)
                        {
                            //开始调用接口，并记录执行时间
                            Stopwatch stopwatch = new Stopwatch();
                            stopwatch.Start();
                            var Response = await _apiService.ExecuteTask(TaskManage);
                            stopwatch.Stop();
                            decimal second = ((decimal)stopwatch.ElapsedMilliseconds / (decimal)1000);

                            //写入执行记录
                            await _mongoDB.GetCollection<Mongo_TaskRecordModel>("Task_Record").InsertOneAsync(new Mongo_TaskRecordModel
                            {
                                TaskName = TaskManage.TaskName,
                                CreateTime = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc),
                                Second = second,
                                GroupName = TaskManage.GroupName,
                                ResponseBody = Response,
                                Method = TaskManage.Method,
                                Url = TaskManage.TaskUrl,
                                RequestBody = TaskManage.RequestBody
                            });
                            result.Success = true;
                            result.Message = "执行成功";
                        }
                    }
                    catch (Exception ex)
                    {
                        //写入错误日志记录
                        await _mongoDB.GetCollection<Mongo_TaskErrorModel>("Task_Error").InsertOneAsync(new Mongo_TaskErrorModel
                        {
                            TaskName = TaskManage.TaskName,
                            CreateTime = DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc),
                            GroupName = TaskManage.GroupName,
                            Message = ex.Message,
                            TaskUrl = TaskManage.TaskUrl,
                            Method = TaskManage.Method,
                            RequestBody = TaskManage.RequestBody
                        });
                        result.Success = false;
                        result.Message = $"执行出错:{ex.Message}";
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 查询执行日志
        /// </summary>
        /// <param name="taskName"></param>
        /// <param name="groupName"></param>
        /// <param name="createTime"></param>
        /// <param name="method"></param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet("QueryTaskRecord")]
        public async Task<PageModel<Mongo_TaskRecordModel>> QueryTaskRecord(string taskName, string groupName, string createTime, string method, int page = 1, int limit = 10)
        {
            Expression<Func<Mongo_TaskRecordModel, bool>> where = m => true;
            if (!taskName.IsNullOrWhiteSpace())
            {
                where = where.And(m => m.TaskName.Contains(taskName));
            }
            if (!groupName.IsNullOrWhiteSpace())
            {
                where = where.And(m => m.GroupName.Contains(groupName));
            }
            if (!createTime.IsNullOrWhiteSpace())
            {
                var TimeBegin = createTime.Split(" - ")[0].ToDateTime();
                var TimeEnd = createTime.Split(" - ")[1].ToDateTime().Value.AddDays(1);
                where = where.And(m => m.CreateTime >= TimeBegin);
                where = where.And(m => m.CreateTime < TimeEnd);
            }
            if (!method.IsNullOrWhiteSpace())
            {
                where = where.And(m => m.Method == method);
            }
            return await _mongoDB.GetCollection<Mongo_TaskRecordModel>("Task_Record").FindPageListAsync(where, m => m.CreateTime, "desc", limit, page);
        }

        /// <summary>
        /// 清空执行日志
        /// </summary>
        /// <returns></returns>
        [HttpDelete("DropTaskRecord")]
        public async Task<ApiResult> DropTaskRecord()
        {
            var res = new ApiResult() { Message = "操作失败", Success = false };
            await _mongoDB.DropCollectionAsync("Task_Record");
            res.Success = true;
            res.Message = "操作成功";
            return res;
        }

        /// <summary>
        /// 查询执行日志
        /// </summary>
        /// <param name="taskName"></param>
        /// <param name="groupName"></param>
        /// <param name="createTime"></param>
        /// <param name="method"></param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet("QueryTaskError")]
        public async Task<PageModel<Mongo_TaskErrorModel>> QueryTaskError(string taskName, string groupName, string createTime, string method, int page = 1, int limit = 10)
        {
            Expression<Func<Mongo_TaskErrorModel, bool>> where = m => true;
            if (!taskName.IsNullOrWhiteSpace())
            {
                where = where.And(m => m.TaskName.Contains(taskName));
            }
            if (!groupName.IsNullOrWhiteSpace())
            {
                where = where.And(m => m.GroupName.Contains(groupName));
            }
            if (!createTime.IsNullOrWhiteSpace())
            {
                var TimeBegin = createTime.Split(" - ")[0].ToDateTime();
                var TimeEnd = createTime.Split(" - ")[1].ToDateTime().Value.AddDays(1);
                where = where.And(m => m.CreateTime >= TimeBegin);
                where = where.And(m => m.CreateTime < TimeEnd);
            }
            if (!method.IsNullOrWhiteSpace())
            {
                where = where.And(m => m.Method == method);
            }
            return await _mongoDB.GetCollection<Mongo_TaskErrorModel>("Task_Error").FindPageListAsync(where, m => m.CreateTime, "desc", limit, page);
        }

        /// <summary>
        /// 清空执行日志
        /// </summary>
        /// <returns></returns>
        [HttpDelete("DropTaskError")]
        public async Task<ApiResult> DropTaskError()
        {
            var res = new ApiResult() { Message = "操作失败", Success = false };
            await _mongoDB.DropCollectionAsync("Task_Error");
            res.Success = true;
            res.Message = "操作成功";
            return res;
        }

        /// <summary>
        /// 查询所有的任务验证配置
        /// </summary>
        /// <returns></returns>
        [HttpGet("QuaryTaskAuth")]
        public async Task<ApiResult<List<Mongo_TaskAuth>>> QuaryTaskAuth()
        {
            var result = new ApiResult<List<Mongo_TaskAuth>>() { Message = "查询失败", Success = false };
            var data = await _mongoDB.GetCollection<Mongo_TaskAuth>("Task_Auth").FindListAsync(m => true);
            if (data != null && data.Count > 0)
            {
                result.Data = data;
                result.Success = true;
                result.Message = "查询成功";
            }
            return result;
        }

        /// <summary>
        /// 查询的任务验证配置
        /// </summary>
        /// <returns></returns>
        [HttpGet("QuaryTaskAuthInfo")]
        public async Task<ApiResult<Mongo_TaskAuth>> QuaryTaskAuthInfo(string guid)
        {
            var result = new ApiResult<Mongo_TaskAuth>() { Message = "查询失败", Success = false };
            var data = await _mongoDB.GetCollection<Mongo_TaskAuth>("Task_Auth").FindInfoAsync(m => m.AuthGuid== guid);
            if (data != null)
            {
                result.Data = data;
                result.Success = true;
                result.Message = "查询成功";
            }
            return result;
        }

        /// <summary>
        /// 查询验证方式分页
        /// </summary>
        /// <param name="authName"></param>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet("QuaryTaskAuthPage")]
        public async Task<PageModel<Mongo_TaskAuth>> QuaryTaskAuthPage(string authName, int page = 1, int limit = 10)
        {
            Expression<Func<Mongo_TaskAuth, bool>> where = m => true;
            if (!authName.IsNullOrWhiteSpace())
            {
                where = where.And(m => m.AuthName.Contains(authName));
            }
            return await _mongoDB.GetCollection<Mongo_TaskAuth>("Task_Auth").FindPageListAsync(where, m => m.CreateTime, "desc", limit, page);
        }

        /// <summary>
        /// 添加验证方式
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost("AddTaskAuth")]
        public async Task<ApiResult> AddTaskAuth([FromBody]Mongo_TaskAuth data)
        {
            var result = new ApiResult { Success = false, Message = "新增失败" };
            if (data != null)
            {
                var Collection = _mongoDB.GetCollection<Mongo_TaskAuth>("Task_Auth");
                if (!data.AuthName.IsNullOrWhiteSpace())
                {
                    var auths = await Collection.FindListAsync(m => m.AuthName == data.AuthName);
                    if (auths.Count > 0)
                    {
                        result.Success = false;
                        result.Message = "此验证方式名已存在";
                        return result;
                    }
                }
                else
                {
                    result.Success = false;
                    result.Message = "请输入验证方式名";
                    return result;
                }
                if (data.AuthUrl.IsNullOrWhiteSpace())
                {
                    result.Success = false;
                    result.Message = "请输入接口地址";
                    return result;
                }
                if (data.UserName.IsNullOrWhiteSpace())
                {
                    result.Success = false;
                    result.Message = "请输入用户名";
                    return result;
                }
                if (data.UserNameField.IsNullOrWhiteSpace())
                {
                    result.Success = false;
                    result.Message = "请输入用户名字段";
                    return result;
                }
                if (data.Psw.IsNullOrWhiteSpace())
                {
                    result.Success = false;
                    result.Message = "请输入密码";
                    return result;
                }
                if (data.PswField.IsNullOrWhiteSpace())
                {
                    result.Success = false;
                    result.Message = "请输入密码字段";
                    return result;
                }
                if (!data.RequestBody.IsNullOrWhiteSpace())
                {
                    if (!data.RequestBody.IsJson())
                    {
                        result.Success = false;
                        result.Message = "请求参数请输入正确的Json格式";
                        return result;
                    }
                }
                if (data.AuthTokenField.IsNullOrWhiteSpace())
                {
                    result.Success = false;
                    result.Message = "请输入返回Token所在的字段";
                    return result;
                }
                if (data.AuthTokenHeader.IsNullOrWhiteSpace())
                {
                    result.Success = false;
                    result.Message = "请输入请求Token所在的头字段";
                    return result;
                }
                if (!data.Token.IsNullOrWhiteSpace())
                {
                    if (!data.Token.IsJson())
                    {
                        result.Success = false;
                        result.Message = "请求头请输入正确的Json格式";
                        return result;
                    }
                }
                await Collection.InsertOneAsync(new Mongo_TaskAuth
                {
                    AuthGuid = Guid.NewGuid().ToString(),
                    AuthName=data.AuthName,
                    AuthUrl=data.AuthUrl,
                    Method = data.Method,
                    UserName = data.UserName,
                    UserNameField = data.UserNameField,
                    Psw = data.Psw,
                    PswField = data.PswField,
                    AuthTokenField = data.AuthTokenField,
                    AuthTokenHeader = data.AuthTokenHeader,
                    RequestBody = data.RequestBody,
                    BodyType = data.BodyType,
                    Token=data.Token,
                    CreateTime= DateTime.SpecifyKind(DateTime.Now, DateTimeKind.Utc),
                });
                result.Success = true;
                result.Message = "新增成功";
            }
            return result;
        }

        /// <summary>
        /// 修改验证方式
        /// </summary>
        /// <param name="guid"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPut("UpdateTaskAuth/{guid}")]
        public async Task<ApiResult> UpdateTaskAuth(string guid, [FromBody] Mongo_TaskAuth data)
        {
            var result = new ApiResult { Success = false, Message = "修改失败" };
            if (data != null)
            {
                var Collection = _mongoDB.GetCollection<Mongo_TaskAuth>("Task_Auth");
                if (!data.AuthName.IsNullOrWhiteSpace())
                {
                    var auths = await Collection.FindListAsync(m => m.AuthName == data.AuthName&&m.AuthGuid!=guid);
                    if (auths.Count > 0)
                    {
                        result.Success = false;
                        result.Message = "此验证方式名已存在";
                        return result;
                    }
                }
                else
                {
                    result.Success = false;
                    result.Message = "请输入验证方式名";
                    return result;
                }
                if (data.AuthUrl.IsNullOrWhiteSpace())
                {
                    result.Success = false;
                    result.Message = "请输入接口地址";
                    return result;
                }
                if (data.UserName.IsNullOrWhiteSpace())
                {
                    result.Success = false;
                    result.Message = "请输入用户名";
                    return result;
                }
                if (data.UserNameField.IsNullOrWhiteSpace())
                {
                    result.Success = false;
                    result.Message = "请输入用户名字段";
                    return result;
                }
                if (data.Psw.IsNullOrWhiteSpace())
                {
                    result.Success = false;
                    result.Message = "请输入密码";
                    return result;
                }
                if (data.PswField.IsNullOrWhiteSpace())
                {
                    result.Success = false;
                    result.Message = "请输入密码字段";
                    return result;
                }
                if (!data.RequestBody.IsNullOrWhiteSpace())
                {
                    if (!data.RequestBody.IsJson())
                    {
                        result.Success = false;
                        result.Message = "请求参数请输入正确的Json格式";
                        return result;
                    }
                }
                if (data.AuthTokenField.IsNullOrWhiteSpace())
                {
                    result.Success = false;
                    result.Message = "请输入返回Token所在的字段";
                    return result;
                }
                if (data.AuthTokenHeader.IsNullOrWhiteSpace())
                {
                    result.Success = false;
                    result.Message = "请输入请求Token所在的头字段";
                    return result;
                }
                if (!data.Token.IsNullOrWhiteSpace())
                {
                    if (!data.Token.IsJson())
                    {
                        result.Success = false;
                        result.Message = "请求头请输入正确的Json格式";
                        return result;
                    }
                }
                await Collection.UpdateAsync(new 
                {
                    AuthName = data.AuthName,
                    AuthUrl = data.AuthUrl,
                    Method = data.Method,
                    UserName = data.UserName,
                    UserNameField = data.UserNameField,
                    Psw = data.Psw,
                    PswField = data.PswField,
                    AuthTokenField = data.AuthTokenField,
                    AuthTokenHeader = data.AuthTokenHeader,
                    RequestBody = data.RequestBody,
                    BodyType = data.BodyType,
                    Token = data.Token
                },new { AuthGuid=data.AuthGuid });
                result.Success = true;
                result.Message = "修改成功";
            }
            return result;
        }

        /// <summary>
        /// 删除验证方式
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        [HttpDelete("DeleteTaskAuth/{guid}")]
        public async Task<ApiResult> DeleteTaskAuth(string guid)
        {
            var result = new ApiResult { Success = false, Message = "删除失败" };
            if (!guid.IsNullOrWhiteSpace())
            {
                await _mongoDB.GetCollection<Mongo_TaskAuth>("Task_Auth").DeleteAsync(new
                {
                    AuthGuid = guid
                });
                _apiService.RemoveAuthToken(guid);
                result.Success = true;
                result.Message = "删除成功";
            }
            return result;
        }

        /// <summary>
        /// 查询邮箱设置
        /// </summary>
        /// <returns></returns>
        [HttpGet("QuaryEmailConfig")]
        public async Task<ApiResult<Mongo_EmailConfig>> QuaryEmailConfig()
        {
            var result = new ApiResult<Mongo_EmailConfig> { Success = false, Message = "查询失败" };
            var data = await _mongoDB.GetCollection<Mongo_EmailConfig>("Email_Config").FindInfoAsync(m => true);
            if (data != null)
            {
                result.Data = data;
                result.Success = true;
                result.Message = "查询成功";
            }
            return result;
        }
        /// <summary>
        /// 查询邮箱设置
        /// </summary>
        /// <returns></returns>
        [HttpPost("SubmitEmail")]
        public async Task<ApiResult> SubmitEmail([FromBody] Mongo_EmailConfig data)
        {
            var result = new ApiResult { Success = false, Message = "提交失败" };
            if (data != null)
            {
                var Collection = _mongoDB.GetCollection<Mongo_EmailConfig>("Email_Config");
                var DBdata = await Collection.FindInfoAsync(m => true);
                if (DBdata != null)
                {
                   await _mongoDB.DropCollectionAsync("Email_Config");
                }
                await Collection.InsertOneAsync(data);
                result.Message = "提交成功";
                result.Success = true;
            }
            return result;
        }
    }
}
